<template>
  <div
    class="relative"
    ref="containerTarget"
    :style="{ height: containerHeight + 'px' }"
  >
    <template v-if="columnWidth && data.length">
      <div
        class="m-waterfall-item absolute duration-300"
        :style="{
          width: columnWidth + 'px',
          left: item._style?.left + 'px',
          top: item._style?.top + 'px'
        }"
        v-for="(item, index) in data"
        :key="nodeKey ? item[nodeKey] : index"
      >
        <slot :item="item" :width="columnWidth" :index="index" />
      </div>
    </template>
    <div v-else>加载中...</div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted, watch, nextTick, onUnmounted } from 'vue'
import {
  getImgElements,
  getAllimgs,
  onComplateImgs,
  getMinHeightColumn,
  getMinHeight,
  getMaxHeight
} from './utils'
const props = defineProps({
  // 数据源
  data: {
    type: Array,
    default: () => []
  },
  // key标识
  nodeKey: {
    type: String
  },
  // 列数
  column: {
    type: Number,
    default: 2
  },
  // 列间距
  columnSpacing: {
    type: Number,
    default: 20
  },
  // 行间距
  rowSpacing: {
    type: Number,
    default: 20
  },
  // 是否预读取
  picturePreReading: {
    type: Boolean,
    default: true
  }
})
watch(
  () => props.data,
  (newValue) => {
    nextTick(() => {
      const resetColumnHeight = newValue.every((item) => !item._style)
      if (resetColumnHeight) {
        useColumnHeightObj()
      }
      if (props.picturePreReading) {
        waitImgComplate()
      } else {
        useItemHeight()
      }
    })
  },
  {
    immediate: true,
    deep: true
  }
)
// 计算容器高度 == 最高一列的高度
const containerHeight = ref(0)
const columnHeightObj = ref({})
const useColumnHeightObj = () => {
  columnHeightObj.value = {}
  for (let i = 0; i < props.column; i++) {
    columnHeightObj.value[i] = 0
  }
}
// 计算容器宽度
const containerTarget = ref(null)
const containerWidth = ref(0)
const containerLeft = ref(0)
const useContainerWidth = () => {
  const { paddingLeft, paddingRight } = getComputedStyle(containerTarget.value)
  containerLeft.value = parseFloat(paddingLeft)
  containerWidth.value =
    containerTarget.value.offsetWidth -
    parseFloat(paddingLeft) -
    parseFloat(paddingRight)
}

// 计算列宽
const columnWidth = ref(0)
const columnSpacingTotal = computed(() => {
  return props.columnSpacing * (props.column - 1)
})
const useColumnWidth = () => {
  useContainerWidth()
  columnWidth.value =
    (containerWidth.value - columnSpacingTotal.value) / props.column
}
onMounted(() => {
  useColumnWidth()
})
// 需要预加载
let itemHeights = []
const waitImgComplate = () => {
  itemHeights = []
  const itemElements = [...document.getElementsByClassName('m-waterfall-item')]
  // 获取image标签
  const imgElements = getImgElements(itemElements)
  // 获取所有的图片地址
  const allImgs = getAllimgs(imgElements)
  onComplateImgs(allImgs).then(() => {
    itemElements.forEach((el, index) => {
      itemHeights.push(el.offsetHeight)
    })
    // 渲染位置
    useItemLocation()
  })
}
// 不需要预加载
const useItemHeight = () => {
  itemHeights = []
  const itemElements = [...document.getElementsByClassName('m-waterfall-item')]
  itemElements.forEach((el, index) => {
    itemHeights.push(el.offsetHeight)
  })
  useItemLocation()
}
// 计算每一项的位置
const useItemLocation = () => {
  props.data.forEach((item, index) => {
    if (item._style) return
    item._style = {}
    item._style.left = getItemLeft()
    item._style.top = getItemTop()
    incresingHeight(index)
  })
  containerHeight.value = getMaxHeight(columnHeightObj.value)
}
// 返回下一个 item 的 left
const getItemLeft = () => {
  const column = getMinHeightColumn(columnHeightObj.value)
  return (
    column * (columnWidth.value + props.columnSpacing) + containerLeft.value
  )
}
const getItemTop = () => {
  return getMinHeight(columnHeightObj.value)
}
// 自增高度
const incresingHeight = (index) => {
  const column = getMinHeightColumn(columnHeightObj.value)
  columnHeightObj.value[column] += itemHeights[index] + props.rowSpacing
}
// 组件销毁时
onUnmounted(() => {
  props.data.forEach((item) => {
    delete item._style
  })
})
const reset = () => {
  setTimeout(() => {
    useColumnWidth()
    props.data.forEach((item) => {
      item._style = null
    })
  }, 100)
}
watch(
  () => props.column,
  () => {
    if (props.picturePreReading) {
      columnWidth.value = 0
      reset()
    } else {
      reset()
    }
  }
)
</script>
